import logging
import cgi
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from models import Category, Feed, DbLog, UserCategories, UserFeeds
from xml.parsers.expat import ExpatError

from xml.dom import minidom

class Uploader(webapp.RequestHandler):
  def post(self):
    opmlStr = self.request.get("opml")
    result = parseOPML(opmlStr)
    if not result:
		self.redirect( "/?&notparsed=true" )	

    self.redirect("/show?&newFeeds=" + str(result[0]) + "&newCats=" + str(result[1]) )


def parseOPML(opmlStr):
    
    currentCategory = ""

    try:
		opmlDom = minidom.parseString(opmlStr)
    except ExpatError:
		return False
    
    rootTagName = opmlDom.documentElement.localName
    if rootTagName != "opml":
        return false
    
    outlines = opmlDom.getElementsByTagName("outline")
    
    #print "<pre>"
    log = DbLog()    
    log.update("Category","total","+1") 
    total = log.getTotal("Category")
    #print total
	
#    return
    
    nOfFeeds = 0
    nOfCats = 0

    for k in outlines: 
        # is a feed
		if k.hasAttribute("xmlUrl"):
		   nOfFeeds += 1
		   f = Feed()
		   f.title = k.getAttribute("title")
		   f.url = k.getAttribute("xmlUrl")
		   f.source = k.getAttribute("htmlUrl")
		   if currentCategory:
				f.category =  currentCategory

		   query = Feed.all().filter("url =",f.url)		
		   results = query.fetch(10)
		   if len(results) <= 0:
			f.put()
		   else:
			f = results[0]
		   
		   uf = UserFeeds()
		   uf.user =  users.get_current_user()
		   uf.feed = f 
		   uf.put()

		else: # is a category
		   nOfCats += 1
		   c = Category()
		   c.title = k.getAttribute("title")
		   
		   query = Category.all().filter("title =", c.title)
		   results = query.fetch(10)
		   if len(results) <= 0:
			  c.put()	
		   else:
				c = results[0]          

				uc = UserCategories()
				uc.user = users.get_current_user()
				uc.category = c

				currentCategory = c
				  

		tmp = k.getAttribute("title")
		#print tmp.encode("UTF-8")
		return [nOfFeeds,nOfCats]

	
    

def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ( '/upload',  Uploader)
  ]))

if __name__ == "__main__":
  main()
  
